<?php

namespace app\api\controller;

use app\common\controller\Frontend;
use think\facade\Db;
use think\facade\Log;
use think\facade\Validate;

class Evaluate extends Frontend
{
    /**
     * 订单评价
     * @return void
     */
    public function evaluate ()
    {
        $post = $this->request->post();

        #validate 验证参数
        $validate = Validate::rule([
            'order_id' => 'require',
            'score'    => 'require',
        ]);

        if (!$validate->check($post)) {
            $this->error($validate->getError());
        }

        $order = \app\api\model\Order::where('id', $post['order_id'])->find();
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order->order_state != 'Completed' || $order->evaluate_state != 'ToBeEvaluated') {
            $this->error('该订单不可评价');
        }


        Db::startTrans();
        try {
            Db::name('order_evaluate')->insert([
                'order_id'      => $post['order_id'],
                'user_id'       => $this->auth->id,
                'technician_id' => $order->technician_id,
                'score'         => $post['score'],
                'content'       => $post['content'],
                'img'           => $post['img'] ?? "",
                'create_time'   => date("Y-m-d H:i:s", time())
            ]);

            $order->evaluate_state = "Reviewed";
            $order->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error("评价失败" . $e->getMessage());
            $this->error("评价失败");
        }


        $this->success('评价成功');
    }

    /**
     * 用户评价列表
     * @return void
     * @throws \think\db\exception\DbException
     */
    public function list ()
    {
        $filed = $this->request->param('filed');
        $id = $this->request->param('id');


        $list = Db::name('order_evaluate')->where($filed, $id)
            ->order('create_time', 'desc')
            ->paginate()->each(function ($item) {
                if (!empty($item->img)) {
                    $img = explode(",", $item->img);
                    foreach ($img as &$v) {
                        $v = IMAGE_URL . $v;
                    }
                    unset($v);
                    $item->img = $img;
                }
                return $item;
            });
        $this->success('', [
            'list'  => $list->items(),
            'total' => $list->total()
        ]);
    }


}